package com.augurit.wf.jbpmex.cmd;

import org.jbpm.api.JbpmException;
import org.jbpm.api.cmd.Environment;
import org.jbpm.pvm.internal.cmd.AbstractCommand;
import org.jbpm.pvm.internal.model.ActivityImpl;
import org.jbpm.pvm.internal.model.ExecutionImpl;
import org.jbpm.pvm.internal.model.ProcessDefinitionImpl;
import org.jbpm.pvm.internal.model.TransitionImpl;
import org.jbpm.pvm.internal.session.DbSession;
import org.jbpm.pvm.internal.session.RepositorySession;

public class CreateTransitionCmd extends AbstractCommand<Void>{
	private static final long serialVersionUID = -5996415196851997153L;
	
	protected String destinationActivityName;
	protected String executionId;

	
	public CreateTransitionCmd( String executionId,String destinationActivityName){
		this.executionId = executionId;
		this.destinationActivityName = destinationActivityName;
	}
	
	public Void execute(Environment environment) throws Exception {
		DbSession dbSession = environment.get(DbSession.class);
		ExecutionImpl execution = (ExecutionImpl)dbSession.findExecutionById(executionId);
		if(executionId == null ||destinationActivityName == null)
			throw new JbpmException("executionId with "+executionId +" does not exist");
		
		//executionId得到的activity,也是新转向transition的source
		ActivityImpl activity = execution.getActivity();
		
		TransitionImpl transition = activity.createOutgoingTransition();
		
		
		transition.setSource(activity);
		transition.setName("to "+this.destinationActivityName);
			
		//获取目标activity
		ProcessDefinitionImpl processDefinition = null;
		RepositorySession repositorySession = environment.get(RepositorySession.class);
		processDefinition = repositorySession.findProcessDefinitionById(execution.getProcessDefinitionId());
		
		ActivityImpl destination = processDefinition.getActivity(this.destinationActivityName);
		transition.setDestination(destination);
		
		return null;
	}
	
	

}
